package com.tsky.system.manager.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.tsky.casing.QueryBean;
import com.tsky.casing.orm.impl.EntityManagerImpl;
import com.tsky.common.BeanUtil;
import com.tsky.system.entity.User;
import com.tsky.system.manager.UserManager;
import com.tsky.system.query.UserQuery;

@Repository("userManager")
public class UserManagerImpl extends EntityManagerImpl implements UserManager {

	public Object userLogin(String username, String password) {
		Criteria ctr = this.getSession().createCriteria(User.class);
		ctr.add(Restrictions.eq("code", username));
		ctr.add(Restrictions.eq("psw", password));

		List<?> resultList = ctr.list();

		return resultList.isEmpty() ? null : resultList.get(0);
	}
	
	public void query(QueryBean queryBean) {
		// TODO Auto-generated method stub
		UserQuery query = (UserQuery) queryBean;
		
		// 基本查询条件
		int page = queryBean.getPage();
		int pageSize = queryBean.getRows(); // page size
		String orderField = queryBean.getSort();
		String sortOrder = queryBean.getOrder();
		
		// 组合查询条件
		String name = query.getName();
		String status = query.getStatus();
		String code = query.getCode();
		String sex = query.getSex();
		String phone = query.getPhone();
		String mobile = query.getMobile();
		String email = query.getEmail();
		String address = query.getAddress();
		String isChargor = query.getIsChargor();
		String departid = query.getDepartid();// 所属部门
		
		Criteria ctr = this.getSession().createCriteria(User.class);

		// 组合查询
		if (!BeanUtil.isEmpty(status) && !"3".equals(status)) {
			ctr.add(Restrictions.eq("status", status));
		}
		
		if (!BeanUtil.isEmpty(sex) && !"3".equals(sex)) {
			ctr.add(Restrictions.eq("sex", sex));
		}
		
		if (!BeanUtil.isEmpty(name)) {
			ctr.add(Restrictions.like("name", "%" + name + "%"));
		}
		
		if (!BeanUtil.isEmpty(code)) {
			ctr.add(Restrictions.like("code", "%" + code + "%"));
		}
		
		if (!BeanUtil.isEmpty(phone)) {
			ctr.add(Restrictions.like("phone", "%" + phone + "%"));
		}
		
		if (!BeanUtil.isEmpty(mobile)) {
			ctr.add(Restrictions.like("mobile", "%" + mobile + "%"));
		}
		
		if (!BeanUtil.isEmpty(email)) {
			ctr.add(Restrictions.like("email", "%" + email + "%"));
		}
		
		if (!BeanUtil.isEmpty(address)) {
			ctr.add(Restrictions.like("address", "%" + address + "%"));
		}
		
		if (!BeanUtil.isEmpty(isChargor)) {
			ctr.add(Restrictions.like("isChargor", "%" + isChargor + "%"));
		}
		
		if (!BeanUtil.isEmpty(departid)) {
			ctr.add(Restrictions.eq("departid", departid));
		}

		// 排序
		if (!BeanUtil.isEmpty(sortOrder)) {
			if ("asc".equals(sortOrder)) {
				ctr.addOrder(Order.asc(orderField));
			} else {
				ctr.addOrder(Order.desc(orderField));
			}
		}
		
		// 总记录数
		List<?> resultList = ctr.list();
		queryBean.setTotal(resultList.size());

		ctr.setFirstResult(pageSize * (page - 1));
		ctr.setMaxResults(pageSize);
		
		queryBean.setDataList(ctr.list());
	}
	
	/**
	 * 查询所有负责人
	 * @param queryBean
	 */
	public void queryAllChargor(QueryBean queryBean) {
		UserQuery query = (UserQuery) queryBean;
		String isChargor = query.getIsChargor();
		
		Criteria ctr = this.getSession().createCriteria(User.class);
		
		if (!BeanUtil.isEmpty(isChargor)) {
			ctr.add(Restrictions.like("isChargor", "%" + isChargor + "%"));
		}
		
		// 总记录数
		List<?> resultList = ctr.list();
		queryBean.setTotal(resultList.size());

		queryBean.setDataList(ctr.list());
	}
	
	/**
	 * 产品配置开发人员时查询用户
	 */
	public void queryUser(QueryBean queryBean) {
		UserQuery query = (UserQuery) queryBean;
		
		// 基本查询条件
		int page = queryBean.getPage();
		int pageSize = queryBean.getRows(); // page size
		String orderField = queryBean.getSort();
		String sortOrder = queryBean.getOrder();
		
		String name = query.getName();
		
		Criteria ctr = this.getSession().createCriteria(User.class);
		
		if (!BeanUtil.isEmpty(name)) {
			ctr.add(Restrictions.like("name", "%" + name + "%"));
		}
		
		ctr.add(Restrictions.eq("status", "1"));
		
		
		// 排序
		if (!BeanUtil.isEmpty(sortOrder)) {
			if ("asc".equals(sortOrder)) {
				ctr.addOrder(Order.asc(orderField));
			} else {
				ctr.addOrder(Order.desc(orderField));
			}
		}
		
		// 总记录数
		List<?> resultList = ctr.list();
		queryBean.setTotal(resultList.size());
		
		ctr.setFirstResult(pageSize * (page - 1));
		ctr.setMaxResults(pageSize);

		queryBean.setDataList(ctr.list());
	}

	/**
	 * 获取权限菜单树
	 * @param userID
	 * @return
	 */
	public String getMenuTree(String userID) {
		List<?> roleMenus = getRoleMenus(userID);

		List mapList = new ArrayList();// JSON菜单集合
		Map cellMap;
		
		for (Object menuInfos : roleMenus) {
			Object[] menu = (Object[]) menuInfos;
			if(menu[3].equals(0)){
				cellMap = new TreeMap();
				cellMap.put("id", menu[0]);
				cellMap.put("text", menu[1]);
				cellMap.put("attributes", new Object[]{menu[2]});
				
				getChildren(cellMap, menu, roleMenus);
				
				mapList.add(cellMap);
			}
		}
		
		String object = null;
		try {
			object = JSONUtil.serialize(mapList);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return object;
		// return JSONArray.fromObject(mapList).toString();
	}
	
	/**
	 * 获取子节点
	 * @param cellMap
	 * @param pMenu
	 * @param roleMenus
	 */
	private void getChildren(Map cellMap, Object[] pMenu, List roleMenus) {
		List childList = new ArrayList();
		Map childMap;
		
		Object pid = pMenu[0];
		for (Object menuInfos : roleMenus) {
			Object[] menu = (Object[]) menuInfos;
			if(pid.equals(menu[4])){
				childMap = new TreeMap();
				childMap.put("id", menu[0]);
				childMap.put("text", menu[1]);
				childMap.put("attributes", new Object[]{menu[2]});
				
				getChildren(childMap, menu, roleMenus);
				
				childList.add(childMap);
			}
		}
		
		if(!pMenu[3].equals(2)){
			cellMap.put("state", "closed");
			cellMap.put("children", childList);
		}
	}
	
	/**
	 * 获取所有菜单节点
	 * @param userid
	 * @return
	 */
	private List getRoleMenus(String userid){
		String sql = "select m.id, m.name, m.url, m.layerNO, m.pid " +
				"from t_SYS_user u, t_SYS_role r, t_SYS_menu m, t_SYS_rolemenu rm "+
				"where u.id=ur.userid "+
				"and r.id=rm.roleid "+
				"and m.id=rm.menuid "+
				"and u.id=? "+
				"order by orderNO";
		
		List resultList = this.getSession().createSQLQuery(sql).setString(0, userid).list();
		return resultList;
	}

	public Object isUniqueCode(String code) {
		// TODO Auto-generated method stub
		Criteria ctr = this.getSession().createCriteria(User.class);
		ctr.add(Restrictions.eq("code", code));
		List<?> resultList = ctr.list();

		return resultList.isEmpty() ? null : resultList.get(0);
	}

	public void queryCommon(UserQuery userQuery) {
		
		// 组合查询条件
		String name = userQuery.getName();
		String status = userQuery.getStatus();
		String code = userQuery.getCode();
		String sex = userQuery.getSex();
		String phone = userQuery.getPhone();
		String mobile = userQuery.getMobile();
		String email = userQuery.getEmail();
		String address = userQuery.getAddress();
		String isChargor = userQuery.getIsChargor();
		String departid = userQuery.getDepartid();// 所属部门
		
		Criteria ctr = this.getSession().createCriteria(User.class);

		// 组合查询
		if (!BeanUtil.isEmpty(status) && !"3".equals(status)) {
			ctr.add(Restrictions.eq("status", status));
		}
		
		if (!BeanUtil.isEmpty(sex) && !"3".equals(sex)) {
			ctr.add(Restrictions.eq("sex", sex));
		}
		
		if (!BeanUtil.isEmpty(name)) {
			ctr.add(Restrictions.like("name", "%" + name + "%"));
		}
		
		if (!BeanUtil.isEmpty(code)) {
			ctr.add(Restrictions.eq("code", code));
		}
		
		if (!BeanUtil.isEmpty(phone)) {
			ctr.add(Restrictions.like("phone", "%" + phone + "%"));
		}
		
		if (!BeanUtil.isEmpty(mobile)) {
			ctr.add(Restrictions.like("mobile", "%" + mobile + "%"));
		}
		
		if (!BeanUtil.isEmpty(email)) {
			ctr.add(Restrictions.like("email", "%" + email + "%"));
		}
		
		if (!BeanUtil.isEmpty(address)) {
			ctr.add(Restrictions.like("address", "%" + address + "%"));
		}
		
		if (!BeanUtil.isEmpty(isChargor)) {
			ctr.add(Restrictions.like("isChargor", "%" + isChargor + "%"));
		}
		
		if (!BeanUtil.isEmpty(departid)) {
			ctr.add(Restrictions.eq("departid", departid));
		}
		
		// 总记录数
		List<?> resultList = ctr.list();
		userQuery.setTotal(resultList.size());

		userQuery.setDataList(resultList);
	}

	@Override
	public <T> List<T> getAllEntityByField(Class<T> classType,
			Map<String, Object[]> fields) {
		// TODO Auto-generated method stub
		return null;
	}

}
